package intelligentcity.model.traffic;

import intelligentcity.model.City;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

// TODO: czyszczenie nieuzywanych samochodow
public class Traffic extends Thread {

    private final City city;
    private final static AtomicInteger counter = new AtomicInteger(0);
    private ConcurrentHashMap<Integer, Car> cars;

    public Traffic(City city, int numberOfCars) {
        this.city = city;
        cars = new  ConcurrentHashMap<>();
        for (int i = 0; i < numberOfCars; i++) {
            cars.put(counter.getAndIncrement(), new Car(city, this, counter.get()));
        }
        for (Integer i : cars.keySet()) {
            cars.get(i).start();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(cars.size());
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int myCounter = counter.getAndIncrement();
            Car car = new Car(city, this, myCounter);
            cars.put(myCounter, car);
            car.start();
        }
    }
    
    public ConcurrentHashMap<Integer, Car> getCars() {
        return cars;
    }

    public City getCity() {
        return city;
    }
}
